<template>
  <el-cascader
    ref="areaElCascader"
    v-model="tempAreaCodes"
    style="width: 100%;"
    :props="props"
    :show-all-levels="showAllLevels"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
  />
</template>

<script>
import { fetchSubAreaList, getParentAreaArray } from '@/api/base/common'

export default {
  name: 'AreaCascader',
  props: {
    // 父组件传来的值
    placeholder: {
      type: String,
      default: '',
      require: false
    },
    disabled: {
      type: Boolean,
      default: false,
      require: false
    },
    clearable: {
      type: Boolean,
      default: false,
      require: false
    },
    showAllLevels: {
      type: Boolean,
      default: false,
      require: false
    },
    value: {
      type: String,
      default: '',
      require: false
    },
    levelLimit: {
      type: Number,
      default: 20,
      require: false
    }
  },
  data() {
    const _this = this
    return {
      currentAreaCodes: [],
      props: {
        // 选择任意一级选项
        checkStrictly: true,
        // 次级菜单的展开方式： click / hover
        expandTrigger: 'click',
        // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
        emitPath: true,
        lazy: true,
        value: 'areaCode',
        label: 'areaName',
        children: 'children',
        leaf: 'leaf',
        lazyLoad(node, resolve) {
          const areaCode = node.level === 0 ? '' : node.data.areaCode
          if (node.level + 1 > _this.levelLimit) {
            resolve([])
          } else {
            fetchSubAreaList(areaCode).then(response => {
              const list = response.data
              if (node.level + 1 === _this.levelLimit && list && list.length > 0) {
                for (const d of list) {
                  d.children = []
                  d.leaf = true
                }
              }
              resolve(list)
            })
          }
        }
      }
    }
  },
  computed: {
    tempAreaCodes: {
      get() {
        return this.currentAreaCodes
      },
      set(newVal) {
        const oldVal = this.currentAreaCodes
        this.currentAreaCodes = newVal
        const newChange = newVal.length > 0 ? newVal.slice(-1)[0] : ''
        const oldChange = oldVal.length > 0 ? oldVal.slice(-1)[0] : ''
        this.$emit('input', newChange)
        this.$emit('change', newChange, oldChange)
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        if (value === null || value === '') {
          this.currentAreaCodes = []
        } else if (this.currentAreaCodes.slice(-1)[0] === value) {
          return
        } else {
          getParentAreaArray(value).then(response => {
            this.currentAreaCodes = response.data ? response.data : []
          })
        }
      }
    }
  }
}
</script>
